Started=false;
//上id#frameModalTopInfoDemo
//下id#fluidModalBottomDangerDemo
//上文本框id TopWarningContent
//下文本框 BottomDangerInfo
function TopHint(content)
{
    document.getElementById("TopWarningContent").innerHTML=content;
    $('#frameModalTopInfoDemo').modal();
}
function DownHint(content)
{
    document.getElementById("BottomDangerInfo").innerHTML=content;
    $('#fluidModalBottomDangerDemo').modal();
}
//绘制Bar图

var namesDataBase=[//随机姓名数据库
    "周祖硕",
    "苦梓晨",
    "祖紫晨",
    "莱一莹",
    "剑子钊",
    "度甜雅",
    "守怡彤",
    "富韵",
    "杭统轩",
    "岑诺曦",
    "藤凌熙",
    "殳子",
    "桑响",
    "储志诚",
    "宋星瑶",
    "汤洋辰",
    "琦正毅",
    "阎雅涵",
    "贲睿",
    "坚倚轩",
    "修炎昊",
    "望涵予",
    "瞿光耀",
    "受浩轩",
    "晁馨冉",
    "融啸天",
    "颜子伯",
    "逯熙然",
    "锺小秋",
    "丘洪滨",
    "邬世博",
    "敛豫豪",
    "梅煜",
    "戊一然",
    "库阳阳",
    "崇景川",
    "瑞岳阳",
    "姚怡博",
    "仪树遥",
    "卢世玉",
    "弘琬晴",
    "牧崇",
    "叶奕",
    "始馨阳",
    "戢若溪",
    "雀梓豪",
    "盈墨",
    "陈悦嘉",
    "城皓",
    "刀自豪",
    "易乙豪",
    "聂涵",
    "曾梓晴",
    "厍曼",
    "璩彤",
    "普灏森",
    "闵娅廷",
    "淡玉茂",
    "次诗琪",
    "嘉晨曦",
    "孙俊鑫",
    "让浩轩",
    "茂景苑",
    "母浩然",
    "蓬路杨",
    "习琪航",
    "中柯汝",
    "续玉灿",
    "籍淑瑶",
    "员子博",
    "贵博",
    "薛金宇",
    "登子墨",
    "树宇航",
    "玉树涵",
    "叔森",
    "来德鑫",
    "贺皓",
    "班子晨",
    "景怡硕",
    "勤子尧",
    "黎泽勋",
    "鄢英旭",
    "在钰珂",
    "充泽睿",
    "卯绮",
    "狂奥翔",
    "钦旭来",
    "邹佳宁",
    "姓殿薇",
    "左雨帆",
    "清路阳",
    "严泰",
    "理米阳",
    "禹翌耀",
    "牵怡玥",
    "裴文轩",
    "机自乐",
    "柏豪",
    "邱浩然",
    "邛子硕",
    "暨楚",
    "呼博潇",
    "程星光",
    "藏轩",
    "暴明硕",
    "栗怡平",
    "计锦锦",
    "贰圣哲",
    "鲁鹏宇",
    "偶绍博",
    "吉文博",
    "弓明昊",
    "苌诗雯",
    "阳世霖",
    "阴子轩",
    "倪钰岩",
    "徐沐言",
    "潭欣奥",
    "连柯",
    "善楠",
    "童世英",
    "以亚龙",
    "蹇俊衡",
    "旅艺诺",
    "改光正",
    "针艺霖",
    "喜邦安",
    "承俊郝",
    "羽光磊",
    "磨长永",
    "完雨泽",
    "燕浩然",
    "靖长春",
    "后惠泽",
    "吴恒鑫",
    "麴志煜",
    "香焦铭",
    "不涵",
    "繁炳硕",
    "蒋子瑄",
    "召宇阳",
    "皇竞兮",
    "谏熙恩",
    "类美蓝",
    "经楠",
    "官晏鸣",
    "表诗",
    "说明月",
    "文紫瑶",
    "独语",
    "扬建云",
    "苟梦鑫",
    "卑沐希",
    "圭久",
    "阙怡冉",
    "烟恩泽",
    "操统赫",
    "悟恒硕",
    "桥晴",
    "丁琪",
    "伦宇轩",
    "窦芸菡",
    "国佳宜",
    "蔚熙晨",
    "田照涵",
    "京妤",
    "封树珂",
    "祭晨硕",
    "随哲铭",
    "詹玉哲",
    "祁一茹",
    "羊昊然",
    "哈滨",
    "威翌岍",
    "咸凌薇",
    "之光星",
    "百爱棋",
    "翠志信",
    "聊子轩",
    "强艺涵",
    "顿毓琳",
    "蒙童",
    "张硕泽",
    "琴梓涵",
    "束洛",
    "夏誉馨",
    "苗伊芃",
    "章玉轩",
    "权恒博",
    "系淇",
    "勾东昇",
    "五梓怡",
    "敏子阳",
    "奕绍桐",
    "金云碧",
    "祢晶晶",
    "戏依依",
    "鲜乐萱",
    "焉玉戈",
    "郦杨",
    "华依诺",
    "车今月",
    "毋智",
    "樊恩宇",
    "潮子聪",
    "恭杰",
    "真俊豪",
    "厉梓艺",
    "廖沐岩",
    "斋毓金",
    "夫树果",
    "秦欣炅",
    "丙一泽",
    "奇智越",
    "竭含平",
    "黄爱丹",
    "端涵",
    "闾龙",
    "路梦森",
    "渠曌煜",
    "泷浩迪",
    "弭光浩",
    "宝洋毅",
    "衅春志",
    "性馨然",
    "碧玉萱",
    "掌豫栋",
    "慈书瑜",
    "萨诺一",
    "仲志青",
    "缪东辰",
    "利诗谣",
    "边淑然",
    "毛树辰",
    "冉润茁",
    "郎悦轩",
    "皋子赫",
    "衡尚昆",
    "本旭东",
    "廉姿言",
    "令诗语",
    "许欣辰",
    "耿奥杰",
    "鄞晓",
    "隽世杰",
    "贾佳沫",
    "丑天",
    "首柯慧",
    "赫海淇",
    "花伊糖",
    "歧记彤",
    "麦梦媛",
    "盛子骞",
    "昔子萱",
    "滕姝贝",
    "布晨妍",
    "洪梓希",
    "罗景源",
    "义泽铭",
    "卿楚",
    "万雨橙",
    "葛艺硕",
    "箕一可",
    "陀莆泽",
    "沈明轩",
    "门梓童",
    "元嘉",
    "忻琳",
    "林宇航",
    "哀昊沅",
    "桓溪纯",
    "南米娅",
    "友自雨",
    "德雯婧",
    "王思晨",
    "信家轩",
    "慎洋博",
    "礼书圻",
    "汗斯",
    "萧欣胜",
    "疏传志",
    "告德超",
    "佛乐萱",
    "印月怡",
    "抗自立",
    "答珞",
    "洛乐",
    "邢欣佑",
    "钊源",
    "脱鸿吉",
    "线子骞",
    "孝欣怡",
    "包山",
    "诗统维",
    "汪雨萱",
    "蛮树森",
    "及胜龙",
    "校遥",
    "凌子辰",
    "朱沐阳",
    "虢奕卓",
    "薄森",
    "寒铭轩",
    "隐林莹",
    "武杰森",
    "莫冰可",
    "前响",
    "象斐然",
    "翦俊浩",
    "斯正宇",
    "佘晴",
    "邴嘉倪",
    "骆雨晨"];
  function CmpWithNumbers(x,y)
  {
    return x-y;
  }
  function genNodes(NodesCount,GroupCount)//根据群组和节点信息生成节点个数
  {
      
      var data={
          array:[]
      }
      for(var i=0;i<NodesCount;i++)
      {
          var temp={
              key:i,groupInfoLen:GroupCount,info:[],fill:go.Brush.randomColor(),text:namesDataBase[i],
              stroke:"black",thick:1
              //thick与stroke指的是边框，而fill指的是原型内部的填充
          }
          var randomInfo=Math.floor(Math.random() *(1<<GroupCount));	
          for(var j=0;j<GroupCount;j++)
          {
              if(randomInfo&(1<<j))
              temp.info.push(true);
              else
              temp.info.push(false);
          }
          data.array.push(temp);
      }
      console.log(data);
      return data;
  }
  function rand_Below(limit)
  {
      return Math.floor(Math.random()*limit);
  }
  function genEdges(NodesCount)
  {
      var Maxedge=NodesCount*(NodesCount-1)/2;
      var edgeCount=Math.floor(Maxedge*0.3);
       Juzhen=[];//邻接矩阵
      for( var i=0;i<NodesCount;i++)
      {
          sli=new Array(NodesCount);
          sli.fill(false);
          Juzhen.push(sli);
      }
      retdata=[];
      for(var i=0;i<edgeCount;i++)
      {
          var x1=rand_Below(NodesCount),x2=rand_Below(NodesCount);
          if(x1!=x2)
          {
              if(x1>x2)
              {
                  var x3=x1;
                  x1=x2;
                  x2=x3;
              }
              Juzhen[x1][x2]=true;
          }
          else
            i--;//没有成功生成边信息
  
      }
      for(var i=0;i<NodesCount;i++)
      {
          for(j=0;j<NodesCount;j++)
          {
              if(Juzhen[i][j])
              retdata.push({from:i,to:j,stroke:"#555",thick:0.3});
          }
      }
      return retdata;
  }
  //使用力导向布局实时的绘制图片
  //注意！注释未清除！！
  function ContinuousForceDirectedLayout() {
      go.ForceDirectedLayout.call(this);
      this._isObserving = false;
    }
    go.Diagram.inherit(ContinuousForceDirectedLayout, go.ForceDirectedLayout);
    ContinuousForceDirectedLayout.prototype.isFixed = function(v) {
      return v.node.isSelected;
    }
    // optimization: reuse the ForceDirectedNetwork rather than re-create it each time
    ContinuousForceDirectedLayout.prototype.doLayout = function(coll) {
      if (!this._isObserving) {
        this._isObserving = true;
        // cacheing the network means we need to recreate it if nodes or links have been added or removed or relinked,
        // so we need to track structural model changes to discard the saved network.
        var lay = this;
  
        this.diagram.addModelChangedListener(function(e) {
          // modelChanges include a few cases that we don't actually care about, such as
          // "nodeCategory" or "linkToPortId", but we'll go ahead and recreate the network anyway.
          // Also clear the network when replacing the model.
          if (e.modelChange !== "" ||
            (e.change === go.ChangedEvent.Transaction && e.propertyName === "StartingFirstTransaction")) {
            lay.network = null;
          }
        });
      }
      var net = this.network;
      if (net === null) {  // the first time, just create the network as normal
        this.network = net = this.makeNetwork(coll);
      } else {  // but on reuse we need to update the LayoutVertex.bounds for selected nodes
        this.diagram.nodes.each(function(n) {
          var v = net.findVertex(n);
          if (v !== null) v.bounds = n.actualBounds;
        });
      }
      // now perform the normal layout
      go.ForceDirectedLayout.prototype.doLayout.call(this, coll);
      // doLayout normally discards the LayoutNetwork by setting Layout.network to null;
      // here we remember it for next time
      this.network = net;
    }
    // end ContinuousForceDirectedLayout
  //初始化画布
  
    function init(NumberOfNodes,NumberOfGroups) {
      Started=true;
      // if (window.goSamples) goSamples();  // init for these samples -- you don't need to call this
      var $ = go.GraphObject.make;  // for conciseness in defining templates
      //整个画图画布的设置
      myDiagram =
        $(go.Diagram, "myDiagramDiv",  // must name or refer to the DIV HTML element
          {
            initialAutoScale: go.Diagram.Uniform,  // an initial automatic zoom-to-fit
            contentAlignment: go.Spot.Center,  // align document to the center of the viewport
            layout:
              $(ContinuousForceDirectedLayout,  // automatically spread nodes apart while dragging
                { defaultSpringLength: 150, defaultElectricalCharge: 140 }),//在这里配置力导向图的各种参数
            // do an extra layout at the end of a move
            "SelectionMoved": function(e) { e.diagram.layout.invalidateLayout(); }//通过函数调用来实时将拖拽的节点调整至力导向布局
          });
          //侦测鼠标拖动
      myDiagram.toolManager.draggingTool.doMouseMove = function() {
       
        go.DraggingTool.prototype.doMouseMove.call(this);
        if (this.isActive) { this.diagram.layout.invalidateLayout(); }
      }
      var PYQ=new Array(202);
      for(var i=0;i<202;i++)
      {
        PYQ[i]=[];
      }
      function Update_CommonFriends()
      {
          var lim=myDiagram.model.linkDataArray.length;
          for (var i=0;i<lim;i++)
          {
            ue=myDiagram.model.linkDataArray[i];
            var u=ue.from;
            var v=ue.to;
            PYQ[u].push(v);
            PYQ[v].push(u);
          }
          for(var i=0;i<202;i++)
          PYQ[i].sort(CmpWithNumbers);
      }
      function commonFriendsAmount(uu,vv)
      {
          //这里犯了一个很傻逼的逻辑错误，过于sb我不想说
          var   retn=0;
          for(var i=0;i<PYQ[uu].length;i++)
            for(var j=0;j<PYQ[vv].length;j++)
                if(PYQ[uu][i]==PYQ[vv][j])
                retn++;
          if(Juzhen[uu][vv]==true||Juzhen[vv][uu]==true)
          retn=0;
          return retn;
      }
      function RelationShip(nodeu,nodev)
      {
        var x=commonFriendsAmount(nodeu.key,nodev.key);
        /*for(var i=0;i<nodeu.groupInfoLen;i++)
             if(nodeu.info[i]==nodev.info[i])
             x++;*/
        /*
        这里有点问题的哦
  
        */
        return x;
    }
    function curWithNames(numcur)
    {
        var nodenw=myDiagram.model.nodeDataArray[numcur]
        return nodenw.text;
    }
    function DrawBar(datas)
{
var ctx = document.getElementById("myChart").getContext('2d');
var myChart = new Chart(ctx, {
  type: 'bar',
  data: {
    labels: [curWithNames(datas[0].cur),curWithNames(datas[1].cur),curWithNames(datas[2].cur),curWithNames(datas[3].cur),curWithNames(datas[4].cur),curWithNames(datas[5].cur)],
    datasets: [{
      label: '横轴是姓名，数轴是共同好友数量',
      data: [datas[0].amount,datas[1].amount,datas[2].amount,datas[3].amount,datas[4].amount,datas[5].amount],
      backgroundColor: [
        'rgba(255, 99, 132, 0.2)',
        'rgba(54, 162, 235, 0.2)',
        'rgba(255, 206, 86, 0.2)',
        'rgba(75, 192, 192, 0.2)',
        'rgba(153, 102, 255, 0.2)',
        'rgba(255, 159, 64, 0.2)'
      ],
      borderColor: [
        'rgba(255,99,132,1)',
        'rgba(54, 162, 235, 1)',
        'rgba(255, 206, 86, 1)',
        'rgba(75, 192, 192, 1)',
        'rgba(153, 102, 255, 1)',
        'rgba(255, 159, 64, 1)'
      ],
      borderWidth: 1
    }]
  },
  options: {
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }]
    }
  }
});
}
      function Cmp(obj1,obj2)
      {
        return obj2.amount-obj1.amount;
      }
      function XiangGuanDudePailie(nodekey)
      {
          ret=[];
          var node=myDiagram.model.nodeDataArray[nodekey];
          var lim=myDiagram.model.nodeDataArray.length;
          for(var i=0;i<lim;i++)
          {
            if(i==nodekey)
            continue;
            else
            {
              tempx=commonFriendsAmount(nodekey,i);;
              //console.log("星星"+tempx.toString()+"与你"+i.toString()+"这样子"+lim.toString());
              //console.log(nodekey);
              ret.push({amount:tempx,cur:i});
            }
          }
          ret.sort(Cmp);
          return ret;
      }
      function nodeClicked(e, obj) {  //在节点被点击的时候调整所有连边的位置
        var evt = e.copy();
        var node = obj.part.data;
        //console.log(node);
        node.fill="white";
        node.thick=6;
        node.stroke="#FF6347";
        myDiagram.model.updateTargetBindings(node);
        var lim=myDiagram.model.linkDataArray.length;
        for(var i=0;i<lim;i++)
          {
            PCR=myDiagram.model.linkDataArray[i];
            if(PCR.from==node.key||PCR.to==node.key)
              {
                //将所有相连的点都设置为黄色
                PCR.stroke="#555";
                PCR.thick=3;
                myDiagram.model.updateTargetBindings(PCR);
              }
        }
        //console.log("1114514");
       // console.log(XiangGuanDudePailie(node.key));
        TopHint("将选中节点的社交网络高亮显示，在下方的图表显示了可能认识的人与关联度");
         DrawBar(XiangGuanDudePailie(node.key));
      }
      // define each Node's appearance
      myDiagram.nodeTemplate =
        $(go.Node, "Auto",  // the whole node panel
          {click:nodeClicked},
          // define the node's outer shape, which will surround the TextBlock
          $(go.Shape, "Circle",
            { fill: "CornflowerBlue", stroke: "black",strokeWidth:1, spot1: new go.Spot(0, 0, 5, 5), spot2: new go.Spot(1, 1, -5, -5) },
            new go.Binding("fill","fill"),
            new go.Binding("stroke","stroke"),
            new go.Binding("strokeWidth","thick")
            ),
          $(go.TextBlock,//由于版本控制需要，此处暂时不设置斜体
            { font: "bold 10pt helvetica, bold arial, sans-serif", textAlign: "center", maxSize: new go.Size(100, NaN) },
            new go.Binding("text", "text"))
        );
      // the rest of this app is the same as samples/conceptMap.html
  
      // replace the default Link template in the linkTemplateMap
      myDiagram.linkTemplate =
        $(go.Link,  // the whole link panel
          $(go.Shape,  // the link shape
            { stroke: "#FF8C00",strokeWidth:1 },
            new go.Binding("stroke","stroke"),
            new go.Binding("strokeWidth","thick")
            )
         
        );
  
      // create the model for the concept map
      
      var data=genNodes(NumberOfNodes,NumberOfGroups);
      var edges=genEdges(NumberOfNodes);
      nodeDataArray=data.array;
      linkDataArray=edges;
      myDiagram.model = new go.GraphLinksModel(nodeDataArray, linkDataArray);
      Update_CommonFriends();
      console.log("coming for PYQ");
      console.log(PYQ);
    }
  
    function reload() {
      //myDiagram.layout.network = null;
      var text = myDiagram.model.toJson();
      myDiagram.model = go.Model.fromJson(text);
      //myDiagram.layout =
      //  go.GraphObject.make(ContinuousForceDirectedLayout,  // automatically spread nodes apart while dragging
      //    { defaultSpringLength: 30, defaultElectricalCharge: 100 });
    }
  var func1=document.getElementById("interect_reset");
  func1.onclick=function()
  {
    if(!Started)
    {  
      DownHint("尚未初始化画布，请先点击初始化");
      return;
    } 
    var lim=myDiagram.model.linkDataArray.length;
          for(var i=0;i<lim;i++)
          {
            PCR=myDiagram.model.linkDataArray[i];
            if(PCR.thick==3)
              {
                PCR.thick=0.3;
                myDiagram.model.updateTargetBindings(PCR);
              }
          }
    lim=myDiagram.model.nodeDataArray.length;
        for(var ix=0;ix<lim;ix++)
        {
            nod=myDiagram.model.nodeDataArray[ix];
            if(nod.fill=="white")
                {
                    nod.fill=go.Brush.randomColor();
                    nod.thick=0.3;
                    nod.stroke="black";
                    myDiagram.model.updateTargetBindings(nod);
                }
        }   
        TopHint("已经清除图上所有标注");    
  }
  var button_Nodes=document.getElementById("DataGen_confirm_Nodes");
  inited=false;
  button_Nodes.onclick=function()
  {
      var inputx=document.getElementById("DataGen_input_Nodes");
      var inputy=document.getElementById("DataGen_input_Group");
       Nodes=parseInt(inputx.value);
       Groups=parseInt(inputy.value);
       inputx.value="";
       inputy.value="";
       if(inited)
       {
         DownHint("只能进行一次初始化");
         return;
       }
       if(Nodes>=0&&Groups>=0)
       {
        init(Nodes,Groups);
        TopHint("已经成功初始化图");  
        inited=true;
        }
       else
       {
         DownHint("请输入正确的信息");
       } 
      
  }
  var buttGroupConfirm=document.getElementById("GroupsConfirm");
  buttGroupConfirm.onclick=function()
  {
      console.log(Groups);
    var inx=document.getElementById("GroupsInput");
    InUn=parseInt(inx.value);
    inx.value="";
    if(InUn<Groups&&InUn>=0)
    {
        TopHint("已经将图中属于该群组的节点高亮显示，请返回图中查看");
        var limmm=myDiagram.model.nodeDataArray.length;
        for(var i=0;i<limmm;i++)
        {
            var OcNode=myDiagram.model.nodeDataArray[i];
            if(OcNode.info[InUn])
            {
                OcNode.fill="white";
                OcNode.thick=6;
                OcNode.stroke="#FF6347";
                myDiagram.model.updateTargetBindings(OcNode);
            }
        }
    }
    else
    {
        DownHint("没有基于该群组的信息，请检查输入！");
    }
  }